#!/usr/bin/evn python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   文件名称 :     consul
   文件功能描述 :   功能描述
   创建人 :       小钟同学
   创建时间 :          2021/12/8
-------------------------------------------------
   修改描述-2021/12/8:         
-------------------------------------------------
"""
from grpcframe.exts.register.base_register import Register
import consul


class ConsulRegister(Register):

    def __init__(self, host, port,server_name,server_id):
        self.host = host
        self.port = port
        self.server_name = server_name
        self.server_id = server_id
        # 服务名称，服务注册的使用用到
        self.c = consul.Consul(host=host, port=port)

    def register(self, address, port) -> bool:
        print(f"GRPC开始注册服务{self.server_name}")
        check = consul.Check.tcp(address, port, "10s")  # 健康检查的ip，端口，检查时间
        if self.c.agent.service.register(name=self.server_name, service_id=self.server_id, address=address, port=port, check=check):  # 注册服务部分
            print(f"GRPC注册服务{self.server_name}成功")
            return True
        else:
            print(f"GRPC注册服务{self.server_name}失败")
            return False

    def deregister(self)-> bool:
        return self.c.agent.service.deregister(self.server_id)

    def get_all_service(self):
        return self.c.agent.services()

    def get_service_name(self,service_name):
        pass


